<?php

namespace app\api\controller;

use app\admin\model\Caigou as CaigouModel;
use app\common\controller\Api;
use addons\epay\library\Service as EpayService;
use EasyWeChat\Foundation\Application as WXPAY_APP;
use EasyWeChat\Payment\Order as WXPAY_ORDER;
use addons\third\model\Third;
use think\Db;
use think\Config;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        // $this->user_id = 2;
        $this->model = new \app\common\model\Order;
        $this->admin_model = new \app\admin\model\Order;
    }  

    /**
    *   我的订单列表(订单状态:10=未支付,20=已支付待发货,30=已发货,40=确认收货 ,50=待报价)
    **/
    public function my_order_list(){
        $return = $this->admin_model->where('user_id',$this->user_id)->order('createtime desc')->select();
        foreach ($return as $key => $value) {
            if(empty($value['goods_name'])){
                $shoppingcar_array = json_decode($value['shoppingcar_id'],true);
                $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                $return[$key]['goods_list'] = $goods_list;
            }
        }
        $this->success('我的订单列表',$return);
    }

    /**
     * 下单
     * @param int $address_id
     * @param int $goods_id
     * @param int $goods_spec_id 产品规格id（单规格和多规格的产品都有该值的）
     * @param int $num
     * @param int $huiyuan 会员情况:10=场内会员,20=场外会员
     * @param int $delivery_methods 送货方式:10=送货上门,20=门店自提
     * @param int $mendian_id 门店id
     */
    public function add_order(){
        $order_detail = $this->model->order_add($this->user_id,input());

        if($order_detail==3){
            $this->error('产品信息为空');
        }else if($order_detail==4){
            $this->error('产品多规格数据丢失，请重新下单');
        }

        $this->success('下单成功');
    }
    /**
     * 订单删除
     * @param string $order_no 订单编号
     */
    public function del(){
        $order_detail = $this->admin_model->where('order_no',input('order_no'))->find();
        if($order_detail['order_status']=='20'||$order_detail['order_status']=='30'||$order_detail['order_status']=='40')$this->error('抱歉，该订单无法删除');
        $res = Db::name('order')->where('order_no',input('order_no'))->delete();
        if($res)$this->success('删除成功');
    }

    /**
     * 订单详情 code是提货码
     * @param string $order_no 订单编号
     */
    public function detail(){
        $return = $this->admin_model->where('order_no',input('order_no'))->order('createtime desc')->find();
            if(empty($return['goods_name'])){
                $shoppingcar_array = json_decode($return['shoppingcar_id'],true);
                $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->select();
                $return['goods_list'] = $goods_list;
            }
        $this->success('订单详情',$return);
    }

     /**
     * 报价的订单支付
     * @param string $order_no 订单编号
     */
    public function order_pay(){
        $order_no = input('order_no');

        $order_detail = Db::name('order')->where('order_no',$order_no)->find();
        // 发起微信支付
        $this->init_wx_pay_for_wxapp();
     
        $third = Third::where(['user_id' => $this->user_id, 'platform' => 'wxapp'])->find();
    
        $payment = $this->wxapp->payment;
       
        $attributes = [
            'trade_type'       => 'JSAPI',
            'body'             => Config::get('site.name'),
            'detail'           => Config::get('site.name'),
            'out_trade_no'     => $order_detail['order_no'],
            'openid'           => $third['openid'],
            'total_fee'        => $order_detail['total_price']*100,
            'notify_url'       => Config::get('site.cdnurl').'api/order/callback_for_wxapp',
        ];

        $order_detail = new WXPAY_ORDER($attributes);
        $result = $payment->prepare($order_detail);
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $prepayId = $result->prepay_id;
            $config = $payment->configForJSSDKPayment($prepayId); // 返回数组
            return $this->success('订单创建成功,预支付成功',$config);
        }
        return $this->error('微信支付调用失败',$result);
    }

    private function init_wx_pay_for_wxapp(){
        $config = get_addon_config('epay');
        $options = [
            'debug'  => false,
            'log' => [
                'level' => 'debug',
                'file'  => LOG_PATH . '/tmp/easywechat.log',
            ],
            'app_id'   => $config['wechat']['miniapp_id'],// 小程序 APPID
            'secret'   => $config['wechat']['app_secret'],//小程序密钥
            'payment' => [
                'merchant_id'        =>  $config['wechat']['mch_id'],//小程序商户号
                'key'                =>  $config['wechat']['key'],//小程序支付密钥
                'notify_url'         =>  \think\Request::instance()->domain().'/api/order/callback_for_wxapp',
            ],

        ];
        $this->wxapp = new WXPAY_APP($options);
    }

     /**
     * 小程序支付回调
     * @ApiSummary  (小程序支付回调)
     * @ApiRoute    (/api/index/callback_for_wxapp)
     */
    public function callback_for_wxapp(){
        $this->init_wx_pay_for_wxapp();
        $response = $this->wxapp->payment->handleNotify(function($notify, $successful){

            if ($successful) {
                $notify_json = json_encode($notify);
                if ($notify['return_code'] === 'SUCCESS') {
                    if($notify["result_code"] === "SUCCESS"){

                        Db::name('order')->where('order_no',$notify->out_trade_no)->where('pay_status',10)->update([
                            'pay_status' => '20',
                            'order_status' => '20',
                            'pay_time' => time(),
                        ]);

                        $order_data = Db::name('order')->where(['order_no'=>$notify->out_trade_no])->field('num,goods_id,goods_spec_id,goods_name,shoppingcar_id,goods_attr')->find();

                        if(empty($order_data['goods_name'])){
                            $shoppingcar_array = json_decode($order_data['shoppingcar_id'],true);
                            $goods_list = Db::name('shoppingcar')->where('id','in',$shoppingcar_array)->field('num,goods_id,goods_name,goods_attr,goods_spec_id')->select();
                            foreach ($goods_list as $key => $value) {
                                $exist_data = CaigouModel::get(['goods_id'=>$value['goods_id'],'goods_spec_id'=>$value['goods_spec_id']]);
                                if($exist_data){
                                    $exist_data->setInc('num',$value['num']);
                                }else{
                                    $cai_data = $value;
                                    $CaigouModel = new CaigouModel();
                                    $CaigouModel->save($cai_data);
                                }
                            }
                        
                        }else{
                            $exist_data = CaigouModel::get(['goods_id'=>$order_data['goods_id'],'goods_spec_id'=>$order_data['goods_spec_id']]);
                            if($exist_data){
                                $exist_data->setInc('num',$order_data['num']);
                            }else{
                                $cai_data['num'] = $order_data['num'];
                                $cai_data['goods_spec_id'] = $order_data['goods_spec_id'];
                                $cai_data['goods_id'] = $order_data['goods_id'];
                                $cai_data['goods_attr'] = $order_data['goods_attr'];
                                $CaigouModel = new CaigouModel();
                                $CaigouModel->save($cai_data);
                            }


                        }

                        

                    }
                }
            }

            return true; // 返回处理完成
            
            
        });
        $response->send();
    }

  

}
